# websocket_tts_server.py
# 豆包大模型TTS WebSocket接口

import os
import uuid
import base64
from fastapi import WebSocket, WebSocketDisconnect, APIRouter, HTTPException
from fastapi.responses import JSONResponse
from .doubao_tts_client import DoubaoTTSClient
from settings import settings

doubao_ws_tts_router = APIRouter()

@doubao_ws_tts_router.websocket("/ws/doubao_tts", name="豆包TTS文字转语音WebSocket接口")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            text = await websocket.receive_text()
            print(f"[豆包TTS] 收到文本: {text}")

            tts_client = DoubaoTTSClient(
                appid=settings.DOUBAO_APP_KEY,
                token=settings.DOUBAO_ACCESS_KEY,
                cluster=settings.DOUBAO_TTS_CLUSTER,
                voice_type=settings.DOUBAO_TTS_VOICE_TYPE,
            )

            async for chunk in tts_client.stream_text_to_audio(text):
                await websocket.send_bytes(chunk)

            await websocket.send_text("[END]")  # 标记结束

    except WebSocketDisconnect:
        print("[豆包TTS] WebSocket disconnected")
    except Exception as e:
        print(f"[豆包TTS] TTS 服务错误：{e}")
        await websocket.close(code=1011)

@doubao_ws_tts_router.post("/doubao_tts/url")
async def doubao_tts_url(request: dict):
    """
    接收 JSON {"text": "..."}，合成语音并返回音频文件 URL。
    """
    text = request.get("text", "").strip()
    if not text:
        raise HTTPException(status_code=400, detail="text 不能为空")

    # 调用豆包 TTS 客户端
    client = DoubaoTTSClient(
        appid=settings.DOUBAO_APP_KEY,
        token=settings.DOUBAO_ACCESS_KEY,
        cluster=settings.DOUBAO_TTS_CLUSTER,
        voice_type=settings.DOUBAO_TTS_VOICE_TYPE,
    )

    # 收集所有音频数据
    audio_chunks = []
    try:
        async for chunk in client.stream_text_to_audio(text):
            audio_chunks.append(chunk)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"豆包TTS 合成失败：{e}")

    # 拼接音频数据
    audio_data = b"".join(audio_chunks)

    # 保存到静态目录
    out_dir = os.path.join("music", "doubao_tts")
    os.makedirs(out_dir, exist_ok=True)
    filename = f"{uuid.uuid4().hex}.pcm"
    file_path = os.path.join(out_dir, filename)
    with open(file_path, "wb") as f:
        f.write(audio_data)
    os.chmod(file_path, 0o644)  # 644 权限：所有者可读写，其他用户可读

    # 返回静态访问 URL
    url = f"/music/doubao_tts/{filename}"
    return JSONResponse({"url": url}) 